//
// Home Controller
//
var geoip = require('geoip-lite');
var fs = require('fs');

module.exports = function(app) {
   
   var home = function(req, res){
      var ip = req.connection.remoteAddress;
      var geo = geoip.lookup(ip);
      if(!geo) geo = {ll: [ 33.9831, -118.0967 ] };
      res.render('home/index', {user: req.user, geo:{lat: geo.ll[0], lng: geo.ll[1]} } ); 
   };
   
   // Home   
   app.route('/')
      .get(home);
   app.route('/home')
      .get(home);

      
      
   // http://thejackalofjavascript.com/uploading-files-made-fun/
   // https://www.npmjs.org/package/blueimp-file-upload-expressjs
   // http://www.javapractices.com/home/HomeAction.do
   //
   //
   // How to Handle File Upload with Node and Express 4.0
   // http://www.e-zest.net/blog/how-to-handle-file-upload-with-node-and-express-4-0/
   // 
   // The Problem:
   // In Express 4.0, Connect is no more a dependency. Besides Connect has already marked multipart () middleware 
   // deprecated and be removed in v3.0. But other middleware (don’t bother, it’s just a fancy word for a module 
   // that does some processing on the request) in Connect are available as separate modules which we can install 
   // individually and use in our app. Well, that may streamline a lot of things for us like individual module 
   // updates, but that also makes all the previous methods of working with Express for file upload obsolete.  
   // 
   // The Solution:
   // This ‘How to’, expects very basic knowledge of Node.js and none of Express! We shall begin with installing 
   // Express, create an express app and then run it. After which we shall add file upload capability using multer 
   // package.
   //
   // So we are going to use “multer”, a middleware (!) that handles “multipart/form-data” and magically makes 
   // the uploaded files and form data available to us in request as request.files and request.body
   //
   // npm install multer
   //
   // app.use(multer({
   //    dest: “./uploads/”
   // }));
   //
   // Front End:
   // form#fileUpload(method="post" action="/uploads" enctype="multipart/form-data")
   //    input(type="file", name="myFile", accept="image/*") 
   //    input(type="submit", value="Upload")
   //
   // Back End:
   app.route('/upload')
      .get(function(req, res){
         res.render('home/upload');
      })
      
      .post(function(req, res){
         if(!req.files.myFile || req.files.myFile.size > 16*1000*1000)
            res.redirect("back", {message: req.flash('uploadMessage')});

         fs.readFile(req.files.myFile.path, function (err, data) {
            var newPath = __dirname + "/public/upload/uploadedFileName";
            fs.writeFile(newPath, data, function (err) {
               res.redirect("back");
            });
         });
      });
};



